import {Component, OnInit} from '@angular/core';
import {FetchService} from "../../../core/net/fetch.service";
import * as _ from "lodash";
import {forkJoin} from "rxjs";
import {UtilService} from "../../../core/util/util.service";

@Component({
    selector: 'app-statistics-overview',
    templateUrl: './statistics-overview.component.html',
    styleUrls: ['./statistics-overview.component.scss']
})
export class StatisticsOverviewComponent implements OnInit {
    mngList = [];
    defaultMngId;
    basePieChartOption = {
        title: {
            zlevel: 0,
            text: '',
            rich: {
                name: {
                    color: '#909399',
                    fontSize: 14,
                    fontWeight: 'normal',
                    lineHeight: 18,
                },
                value: {
                    color: '#3d3d3d',
                    fontSize: 18,
                    fontWeight: 'bold',
                    lineHeight: 22,
                },
            },
            top: 'center',
            left: '145',
            textAlign: 'center',
            textStyle: {
                rich: {
                    name: {
                        color: '#909399',
                        fontSize: 14,
                        fontWeight: 'normal',
                        lineHeight: 18,
                    },
                    value: {
                        color: '#3d3d3d',
                        fontSize: 18,
                        fontWeight: 'bold',
                        lineHeight: 22,
                    },
                },
            },
        },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        color: ['#637efe', '#ffc209', '#0094f0', '#d2e2ff'],
        legend: {
            orient: 'vertical',
            x: 'right',
            data: [],
            itemGap: 15,
            top: 'middle',
            align: 'left',
            icon: 'circle',
            // formatter: name =>  {
            //     return name;
            // }
        },
        series: [
            {
                name: '',
                type: 'pie',
                radius: ['80%', '89%'],
                center: [150, '50%'],
                stillShowZeroSum: false,
                avoidLabelOverlap: false,
                zlevel: 1,
                label: {
                    normal: {
                        padding: [20, 20, 20, 20],
                        backgroundColor: '#fff',
                        show: false,
                        position: 'center',
                        rich: {
                            name: {
                                color: '#909399',
                                fontSize: 14,
                                fontWeight: 'normal',
                                lineHeight: 18,
                            },
                            value: {
                                color: '#3d3d3d',
                                fontSize: 18,
                                fontWeight: 'bold',
                                lineHeight: 22,
                            },
                        },
                    },
                    emphasis: {
                        show: true,
                        textStyle: {
                            fontSize: '16',
                            fontWeight: 'bold'
                        }
                    }
                },
                labelLine: {
                    normal: {
                        show: false
                    }
                },
                data: []
            }
        ]
    };
    pieChartOpt1 = {};
    pieChartOpt2 = {};
    pieChartOpt3 = {};
    pieChartOpt4 = {};
    pieTotal1 = 0;
    pieTotal2 = 0;
    pieTotal3 = 0;
    pieTotal4 = 0;
    baseBarChartOption = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                crossStyle: {
                    color: '#999'
                }
            }
        },
        color: ['#81d5ef', '#7980f1', '#0d83bf', '#89b0ae', '#4b707b'],
        legend: {
            bottom: 10,
            data: []
        },
        xAxis: [
            {
                type: 'category',
                data: [],
                axisPointer: {
                    type: 'shadow'
                }
            }
        ],
        yAxis: [
            {
                type: 'value',
                name: '',
                axisLabel: {
                    formatter: '{value}'
                }
            }
        ],
        series: []
    };
    barChartOpt1 = {};
    barChartOpt2 = {};
    barChartOpt3 = {};
    tableData = [];
    tableHead = [];

    /********* 各管理处 ***********/
    planNum1 = 0;
    completion1 = 0;
    percentage1 = 0;
    planNum2 = 0;
    completion2 = 0;
    percentage2 = 0;
    isEcoShow = true;
    lineBaseOpt: any = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                animation: false,
                label: {
                    backgroundColor: '#505765'
                }
            }
        },
        color: ['#289df5', '#fbc01b'],
        legend: {
            data: ["水位", "流量"],
            bottom: 10
        },
        xAxis: {
            type: "category",
            data: []
        },
        yAxis: [
            {
                name: "水位(m)",
                type: "value"
            },
            {
                name: "流量(m³/s)",
                type: "value"
            }
        ],
        series: [
            {
                name: "水位",
                type: "line",
                smooth: true,
                data: []
            },
            {
                name: "流量",
                type: "line",
                yAxisIndex: 1,
                smooth: true,
                data: []
            }
        ]
    };
    lineChartOpt = {};
    countyList = [];
    countyId;
    ghList = [
        {
            label: '固海扬水',
            value: 'GHYS'
        },
        {
            label: '固海扩灌',
            value: 'GHKG'
        }
    ];
    ghValue = 'GHYS';
    isGhShow = false;
    tableData2 = [];
    tableHead2 = [];

    constructor(private fetchService: FetchService,
                private util: UtilService) {
    }

    ngOnInit(): void {
        this.fetchService.get('report/muw/list', {}).subscribe(res => {
            if (res && Array.isArray(res)) {
                this.mngList = res;
                if (this.mngList.length) {
                    this.defaultMngId = this.mngList[0].id;
                    this.mngOnChanged(this.defaultMngId);
                }
            }
        });
    }

    formatPercentage = (percent: number) => ``;

    mngOnChanged(id): void {
        const params = {id: id};
        console.log(this.defaultMngId);
        this.isGhShow = id === 11;
        if (id === 1) {
            const queryInletData = this.fetchService.post('report/muw/statistic1', params);   //  引水统计
            const queryUseWaterData = this.fetchService.post('report/muw/statistic2', params);   //  各业用水
            const queryTakeWaterData = this.fetchService.post('report/muw/statistic3', params);   //  取水口取水
            const queryTargetData = this.fetchService.post('report/muw/statistic4', params);   //  用水指标
            const queryCropData = this.fetchService.post('report/muw/statistic5', params);   //  作物种植面积
            const queryTableData = this.fetchService.post('report/muw/statistic6', params);   //  表格
            const queryTakeTargetData = this.fetchService.post('report/muw/statistic7', params);   //  取水指标
            forkJoin(queryInletData,
                queryUseWaterData,
                queryTakeWaterData,
                queryTargetData,
                queryCropData,
                queryTableData,
                queryTakeTargetData).subscribe(res => {
                if (res) {
                    this.pieTotal1 = this.util.sum(this.util.getItemValues(res[0], 'val', true));
                    this.pieTotal2 = this.util.sum(this.util.getItemValues(res[4], 'val', true));
                    this.pieTotal3 = this.util.sum(this.util.getItemValues(res[3], 'val', true));
                    this.pieTotal4 = this.util.sum(this.util.getItemValues(res[6], 'val', true));

                    this.pieChartOpt1 = this.getPieChartData(res[0], '引水量', '总引水', '亿方', this.pieTotal1, ['#637efe', '#ffc209', '#0094f0', '#d2e2ff']);
                    this.pieChartOpt2 = this.getPieChartData(res[4], '种植面积', '总面积', '万亩', this.pieTotal2, ['#637efe', '#b6e49d', '#0094f0', '#d2e2ff']);
                    this.pieChartOpt3 = this.getPieChartData(res[3], '用水指标', '各业用水指标', '亿方', this.pieTotal3, ['#637efe', '#7ed6f1', '#0094f0', '#d2e2ff']);
                    this.pieChartOpt4 = this.getPieChartData(res[6], '取水指标', '取水口取水指标', '亿方', this.pieTotal4, ['#637efe', '#ffc209', '#0094f0', '#d2e2ff']);

                    this.barChartOpt1 = this.getBarChartData(res[1], '用水量（亿方）');
                    this.barChartOpt2 = this.getBarChartData(res[2], '取水量（亿方）');
                    this.tableHead = Object.keys(res[5]).map(item => {
                        return {
                            title: item,
                            inletProp: item + '_inlet',
                            planProp: item + '_plan',
                            compProp: item + '_comp'
                        };
                    });
                    const tableData = res[5][Object.keys(res[5])[0]].map(o => {
                        return {
                            name: o['name']
                        };
                    });

                    this.tableHead.forEach(key => {
                        tableData.forEach((item, index) => {
                            const nameObj = res[5][key.title];
                            item[key.inletProp] = nameObj[index]['inlet'];
                            item[key.planProp] = nameObj[index]['plan'];
                            item[key.compProp] = nameObj[index]['completion'];
                        });
                    });

                    this.tableData = tableData;
                }
            });
        } else {
            const countyParams = _.cloneDeep(params);
            if (this.isGhShow) {
                _.assign(countyParams, {
                    classify: this.ghValue
                });
            }
            const queryData1 = this.fetchService.post('report/muw/statistic8', params);   //  农业用水
            const queryData2 = this.fetchService.post('report/muw/statistic12', params);   //  生态用水
            const queryData3 = this.fetchService.post('report/muw/statistic11', params);   //  灌溉面积
            const queryData4 = this.fetchService.post('report/muw/statistic14', params);   //  种植结构
            const queryData5 = this.fetchService.post('report/muw/statistic9', countyParams);   //  市县用水
            const queryData6 = this.fetchService.post('report/muw/statistic10', params);   //  水位流量曲线
            const queryData7 = this.fetchService.post('report/muw/statistic13', countyParams);   //  表格
            forkJoin(queryData1,
                queryData2,
                queryData3,
                queryData4,
                queryData5,
                queryData6,
                queryData7).subscribe(res => {
                if (res) {
                    const pieTotal3 = this.util.sum(this.util.getItemValues(res[2], 'val', true));
                    const pieTotal4 = this.util.sum(this.util.getItemValues(res[3], 'val', true));

                    this.planNum1 = res[0].plan;
                    this.completion1 = res[0].inlet;
                    this.percentage1 = res[0].completion * 100;
                    this.isEcoShow = !!res[1];
                    if (this.isEcoShow) {
                        this.planNum2 = res[1].plan;
                        this.completion2 = res[1].inlet;
                        this.percentage2 = res[1].completion * 100;
                    }
                    this.pieChartOpt3 = this.getMngPieChartData(res[2], '灌溉面积', '灌溉面积', '万亩', pieTotal3, ['#637efe', '#7ed6f1', '#0094f0', '#d2e2ff'], true);
                    this.pieChartOpt4 = this.getMngPieChartData(res[3], '作物面积', '总计', '万亩', pieTotal4, ['#637efe', '#ffc209', '#0094f0', '#d2e2ff']);

                    this.barChartOpt3 = {
                        legend: {
                            data: []
                        },
                        xAxis: [
                            {
                                data: res[4].map(item => {
                                    return item.name;
                                }),
                            }
                        ],
                        yAxis: [
                            {
                                name: '用水量（亿方）',
                            },
                        ],
                        series: [{
                            name: '用水量',
                            type: 'bar',
                            barWidth: 10,
                            itemStyle: {
                                emphasis: {
                                    barBorderRadius: [5, 5, 0, 0]
                                },
                                normal: {
                                    barBorderRadius: [5, 5, 0, 0]
                                }
                            },
                            data: res[4].map(item => {
                                return item.val;
                            })
                        }]
                    };
                    this.countyList = res[5];
                    this.countyId = this.countyList[0].id;
                    this.countyOnChange();

                    this.tableHead2 = Object.keys(res[6]).map(item => {
                        return {
                            title: item,
                            valProp: item + '_val',
                        };
                    });
                    const tableData = res[6][Object.keys(res[6])[0]].map(o => {
                        return {
                            name: o['name']
                        };
                    });

                    this.tableHead2.forEach(key => {
                        tableData.forEach((item, index) => {
                            const nameObj = res[6][key.title];
                            item[key.valProp] = nameObj[index]['val'];
                        });
                    });

                    this.tableData2 = tableData;
                }
            });
        }
    }

    getPieChartData(data, seriesName, title, unit, total, color): any {
        return {
            title: {
                text: [
                    '{name|' + title + '}',
                    '{value|' + total + '}',
                    '{value|' + unit + '}'
                ].join('\n')
            },
            color: color,
            legend: {
                data: data.map(item => {
                    return item.name;
                }),
                formatter: name => {
                    const target = _.find(data, o => {
                        return o.name === name;
                    }).val;
                    return name + ' ' + ((target / total) * 100).toFixed(2) + '%';
                    // return name + ' ' + target + unit +  '' + ((target / total) * 100).toFixed(2) + '%';
                }
            },
            series: [
                {
                    name: seriesName,
                    label: {
                        normal: {
                            formatter: [
                                '{name|{b}}',
                                '{value|{c}}',
                                '{value|' + unit + '}'
                            ].join('\n')
                        }
                    },
                    data: data.map(item => {
                        return {
                            value: item.val,
                            name: item.name
                        };
                    })
                }
            ]
        };
    }

    getBarChartData(data, yAxisName): any {
        const seriesData = data.list.map(item => {
            return {
                name: item.name,
                type: 'bar',
                barWidth: 10,
                itemStyle: {
                    emphasis: {
                        barBorderRadius: [5, 5, 0, 0]
                    },
                    normal: {
                        barBorderRadius: [5, 5, 0, 0]
                    }
                },
                data: item.data
            };
        });
        seriesData.push({
            name: '总计',
            type: 'line',
            smooth: true,
            itemStyle: {
                normal: {
                    color: '#4b707b', // 折线条的颜色
                    borderColor: '#4b707b', // 拐点边框颜色
                    areaStyle: {
                        type: 'default',
                        opacity: 0.1
                    }
                },
                emphasis: {
                    barBorderRadius: 7
                },
            },
            data: data.total
        });
        const legendData = data.list.map(item => {
            return item.name;
        });
        legendData.push('总计');
        return {
            legend: {
                data: legendData
            },
            xAxis: [
                {
                    data: data.years.map(item => {
                        return item;
                    }),
                }
            ],
            yAxis: [
                {
                    name: yAxisName,
                },
            ],
            series: seriesData
        };
    }

    //  管理处处理
    getMngPieChartData(data, seriesName, title, unit, total, color, percentage?): any {
        return {
            title: {
                text: [
                    '{name|' + title + '}',
                    '{value|' + total + '}',
                    '{value|' + unit + '}'
                ].join('\n')
            },
            color: color,
            legend: {
                data: data.map(item => {
                    return item.name;
                }),
                formatter: name => {
                    const target = _.find(data, o => {
                        return o.name === name;
                    });
                    if (!percentage) {
                        return name + ' ' + target.val + unit;
                    } else {
                        return name + ' 占计划：' + (target['completion'] * 100).toFixed(2) + '%';
                        // return name + ' 已灌：' + target.val + unit + ' 占计划：' + (target['completion'] * 100).toFixed(2) + '%';
                    }
                }
            },
            series: [
                {
                    name: seriesName,
                    label: {
                        normal: {
                            formatter: [
                                '{name|{b}}',
                                '{value|{c}}',
                                '{value|' + unit + '}'
                            ].join('\n')
                        }
                    },
                    data: data.map(item => {
                        return {
                            value: item.val,
                            name: item.name
                        };
                    })
                }
            ]
        };
    }

    countyOnChange(): void {
        console.log(this.countyId);
        const data = _.find(this.countyList, item => {
            return item.id === this.countyId;
        });
        this.lineChartOpt = {
            xAxis: [
                {
                    data: data.list.map(item => {
                        return item.date;
                    }),
                }
            ],
            series: [
                {
                    name: '水位',
                    type: 'line',
                    itemStyle: {
                        normal: {
                            color: '#289df5', // 折线条的颜色
                            borderColor: '#289df5', // 拐点边框颜色
                            areaStyle: {
                                type: 'default',
                                opacity: 0.1
                            }
                        }
                    },
                    data: data.list.map(item => {
                        return item.level;
                    })
                },
                {
                    name: '流量',
                    type: 'line',
                    itemStyle: {
                        normal: {
                            color: '#fbc01b',
                            borderColor: '#fbc01b',
                            areaStyle: {
                                type: 'default',
                                opacity: 0.1
                            }
                        }
                    },
                    data: data.list.map(item => {
                        return item.flow;
                    })
                }
            ]
        };
    }

    ghOnChange(): void {
        this.barChartOpt3 = {};
        this.tableData2 = [];
        this.tableHead2 = [];
        this.fetchService.post('report/muw/statistic9', {
            id: this.defaultMngId,
            classify: this.ghValue
        }).subscribe(res => {
            if (Array.isArray(res)) {
                this.barChartOpt3 = {
                    legend: {
                        data: []
                    },
                    xAxis: [
                        {
                            data: res.map(item => {
                                return item.name;
                            }),
                        }
                    ],
                    yAxis: [
                        {
                            name: '用水量（亿方）',
                        },
                    ],
                    series: [{
                        name: '用水量',
                        type: 'bar',
                        barWidth: 10,
                        itemStyle: {
                            emphasis: {
                                barBorderRadius: [5, 5, 0, 0]
                            },
                            normal: {
                                barBorderRadius: [5, 5, 0, 0]
                            }
                        },
                        data: res.map(item => {
                            return item.val;
                        })
                    }]
                };
            }
            this.fetchService.post('report/muw/statistic13', {
                id: this.defaultMngId,
                classify: this.ghValue
            }).subscribe(res2 => {
                if (Object.keys(res2).length) {
                    this.tableHead2 = Object.keys(res2).map(item => {
                        return {
                            title: item,
                            valProp: item + '_val',
                        };
                    });
                    const tableData = res2[Object.keys(res2)[0]].map(o => {
                        return {
                            name: o['name']
                        };
                    });

                    this.tableHead2.forEach(key => {
                        tableData.forEach((item, index) => {
                            const nameObj = res2[key.title];
                            item[key.valProp] = nameObj[index]['val'];
                        });
                    });
                    this.tableData2 = tableData;
                }
            });
        });
    }

    queryInfo(): void {

    }
}
